package com.joint.web.action.mp;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.bean.EnumManage;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.entity.system.Admin;
import com.joint.base.entity.system.Locations;
import com.joint.base.mp.WxEchoMpMessageRouter;
import com.joint.base.mp.WxEchoMpServiceImpl;
import com.joint.base.mp.WxMpInCacheConfigStorage;
import com.joint.base.service.AdminService;
import com.joint.base.service.UsersService;
import com.joint.base.service.jms.AdvancedNotifyMessageProducer;
import com.joint.base.util.DataUtil;
import com.joint.base.util.StringUtils;
import com.joint.core.entity.ProAttend;
import com.joint.core.entity.ProInfo;
import com.joint.core.entity.ProSignIn;
import com.joint.core.service.ProAttendService;
import com.joint.core.service.ProInfoService;
import com.joint.core.service.ProSignInService;
import com.joint.web.action.BaseController;
import fz.me.chanjar.weixin.common.bean.WxJsapiSignature;
import fz.me.chanjar.weixin.common.exception.WxErrorException;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 后台Action类 - 微信首页
 * ============================================================================
 * 版权所有 2014 min_xu。
 * ----------------------------------------------------------------------------
 *
 * @author min_xu
 *
 * @version 1.1 2014-3-31
 */
@Controller("mpProinfo")
@RequestMapping("/mp")
public class AjaxProinfoController extends BaseController {
    private static final long serialVersionUID = -5383463207248344967L;

    @Resource
    private ProInfoService proInfoService;
    @Resource
    private ProSignInService proSignInService;
    @Resource
    private ProAttendService proAttendService;
    @Resource
    private WxEchoMpServiceImpl wxMpService;
    @Resource
    private WxEchoMpMessageRouter wxEchoMpMessageRouter;
    @Resource
    private WxEchoMpMessageRouter wxMpMessageRouter;
    @Resource
    private WxMpInCacheConfigStorage wxMpInCacheConfigStorage;
    @Resource
    private AdvancedNotifyMessageProducer notifyMessageProducer;
    @Resource
    private AdminService adminService;

    @Resource
    private UsersService usersService;

    private List<ProInfo> proInfoList;

    private ProInfo proInfo;

    private String searchString;
    private WxJsapiSignature jsapiSignature;

    // 0(未完成)，1已完成
    private String proStatusType;

    private String latitude;
    private String longitude;
    private  Map<String,List<Map<String,Object>>> userListMap;

    @RequestMapping(value = "/ajax-proInfo/list/{proStatusType}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int page,String pageKeyword,@PathVariable("proStatusType") String proStatusType){
        List<Map<String, Object>> dataRows =Lists.newArrayList();
        JSONObject data = new JSONObject();
        Map<String,Object> rmap;
        pager = new Pager();
        pager.setPageSize(10);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        Map<String, Object> map = Maps.newHashMap();
        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        if(StringUtils.isNotEmpty(pageKeyword)){
            map.put("name", pageKeyword);
        }
        //LogUtil.info("proStatusType:" + proStatusType);
        if (StringUtils.isNotEmpty(proStatusType)){
            if(proStatusType.equals("0")){
                map.put("proState", 0);
            }else{
                map.put("proState", 1);
            }
        }
        Company com=usersService.getCompanyByUser();
        pager = proInfoService.findByPagerAndLimit(pager,usersService.getLoginInfo(),usersService.getCompanyByUser(),map);
        proInfoList= (List<ProInfo>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
        for(ProInfo proInfo:proInfoList){
            rmap=Maps.newHashMap();
            rmap.put("url",getPath()+"mp/ajax-proInfo/read/"+proInfo.getId());
            rmap.put("name",proInfo.getName());
            rmap.put("client",proInfo.getClient().getName());
            rmap.put("chief",proInfo.getChief().getName());
            rmap.put("province",proInfo.getProvince());
            dataRows.add(rmap);
        }
        data.put("pageNum", pager.getPageNumber());//页数
        data.put("pageSize", dataRows.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("pageKeyword", pager.getKeyword()==null?"": pager.getKeyword());//查询
        data.put("dataRows", dataRows);//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));

    }

    @RequestMapping(value = "/ajax-proInfo/listRelated", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> listRelated(int page,String pageKeyword){
        List<Map<String, Object>> dataRows =Lists.newArrayList();
        JSONObject data = new JSONObject();
        Map<String,Object> rmap;

        pager = new Pager();
        pager.setPageSize(7);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        Users users = usersService.getLoginInfo();
        Map<String,Object> params=Maps.newHashMap();
        params.put("proState",0);
        params.put("state", BaseEnum.StateEnum.Enable);
        //pager = proInfoService.findByPagerAndUsersRelated(pager,users,usersService.getCompanyByUser(),params);
        pager=proInfoService.findByPagerAndLimit(pager,users,usersService.getCompanyByUser(),params);
        proInfoList = (List<ProInfo>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());

        for(ProInfo proInfo:proInfoList){
            rmap=Maps.newHashMap();
            rmap.put("id",proInfo.getId());
            rmap.put("name",proInfo.getName());
            rmap.put("chief",proInfo.getChief().getName());
            rmap.put("province",proInfo.getProvince());
            dataRows.add(rmap);
        }
        data.put("pageNum", pager.getPageNumber());//页数
        data.put("pageSize", dataRows.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("pageKeyword", pager.getKeyword()==null?"": pager.getKeyword());//查询
        data.put("dataRows", dataRows);//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    public String read(){
        try {
            jsapiSignature =  wxMpService.createJsapiSignature(getRequest().getRequestURL()+"?keyId="+keyId);
            jsapiSignature.setAppId(wxMpInCacheConfigStorage.getAppId());
            //LogUtil.info("appId:" + jsapiSignature.getAppId() );
        } catch (WxErrorException e) {
            LogUtil.info(e);
        }
        if(StringUtils.isEmpty(keyId)) return "index";
        proInfo = proInfoService.get(keyId);
        userListMap = Maps.newLinkedHashMap();
        Pager upager = new Pager(0);
        upager.setOrderBy("pinYinHead");

        upager.setOrderType(BaseEnum.OrderType.asc);
        List<Users> usersList = (List<Users>) usersService.findByPagerAndCompany(upager, null,usersService.getCompanyByUser(), new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        for(Users users : usersList){
            List<Map<String,Object>> tmplist =Lists.newArrayList();
            Map<String,Object> rmap=Maps.newHashMap();
            String pinyinHead = users.getPinYinHead();
            String headstr = "";
            if(pinyinHead != null){
                headstr = StringUtils.upperCase(String.valueOf(pinyinHead.charAt(0)));
            }
            rmap.put("id",users.getId());
            rmap.put("name",users.getName());
            rmap.put("checked","");
            tmplist.add(rmap);
            userListMap.put(headstr, tmplist);
        }
        return "read";
    }


    /**
     * 签到
     * updated by zhucx
     * 修正签到
     * @return
     * @throws Exception
     */
    public Map<String,Object> assign() throws Exception {
        Users users = usersService.getLoginInfo();
        String userId = users.getId();
        Company company = users.getCompany();
        Admin admin = adminService.get(users.getAdminId());
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlAppResult(404, "尚未选择项目！", null);
        }
        boolean userFlag = false;
        proInfo = proInfoService.get(keyId);
        Users userChief = proInfo.getChief();
        List<Users> listUsers = (List<Users>) proInfoService.findByProInfoPager(new Pager(0),null,null,proInfo,null).getList();
        if(userChief.getId().equals(userId)){
            userFlag = true;
        }else{
            for(Users tmp: listUsers){
                if(tmp.getId().equals(userId)){
                    userFlag = true;
                    break;
                }
            }
        }
        if(!userFlag){
            return ajaxHtmlAppResult(404, "您不是该项目组成员,无法签到！", null);
        }
        //该用户当天已经进行了基础签到
        Date now = new Date();
        Date now1 = DataUtil.StringToDate(DataUtil.DateToString(now, "yyyy/MM/dd"), "yyyy/MM/dd");
        Date now2 = DataUtil.StringToDate(DataUtil.DateToString(DataUtil.getAfterDay(now, 1), "yyyy/MM/dd"), "yyyy/MM/dd");
        HashMap<String,Object> params = new HashMap<String,Object>();
        params.put("proInfo", proInfo);
        List<ProSignIn> proSigninList = (List<ProSignIn>) proSignInService.findByPagerAndCompany(new Pager(0), "modifyDate", now1, now2, users, company, params).getList();

        //根据后台设定考勤时间点的时间区间，签到时间不在正常和异常时间区间内的，提示用户：“时间未到，不能签到。”
        String stime = DataUtil.DateToString(now, "HH:mm:ss");
        now = DataUtil.StringToDate(stime, "HH:mm:ss");

        Pager pagerPA = new Pager(0);
        pagerPA = proAttendService.findByPagerAndProInfo(pager,proInfo,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        List<ProAttend> proAttendList = (List<ProAttend>) pagerPA.getList();

        if (proAttendList.size()==0){
            return ajaxHtmlAppResult(404, "该项目尚未设定考勤时间！", null);
        }

        boolean flag = false;
        int status = 0;
        int hasSigned;
        for(ProAttend pa:proAttendList){
            Date ars = pa.getRegularStart();
            Date are = pa.getRegularEnd();
            Date aurs = pa.getUnRegularStart();
            Date aure = pa.getUnRegularEnd();

            hasSigned = 0;
            if ( proSigninList != null ) {
                for(ProSignIn ps:proSigninList){
                    Date mdate = DataUtil.StringToDate(DataUtil.DateToString(ps.getModifyDate(), "HH:mm:ss"), "HH:mm:ss");
                    if ((DataUtil.TimeDiff(mdate, ars)>=0 && DataUtil.TimeDiff(mdate, are)<60000) || (DataUtil.TimeDiff(mdate, aurs)>=0 && DataUtil.TimeDiff(mdate, aure)<60000)) {
                        hasSigned = 1;
                        break;
                    }
                }
            }

            if (DataUtil.TimeDiff(now, ars)>=0 && DataUtil.TimeDiff(now, are)<60000) {
                if(hasSigned == 1){
                    return ajaxHtmlAppResult(404, "每个考勤区间只能进行一次签到，不能重复签到！", null);
                }
                flag = true;
                status = 1;
                break;
            }

            if (DataUtil.TimeDiff(now, aurs)>=0 && DataUtil.TimeDiff(now, aure)<60000){
                if(hasSigned == 1){
                    return ajaxHtmlAppResult(404, "每个考勤区间只能进行一次签到，不能重复签到！", null);
                }
                flag = true;
                status = 0;
                break;
            }

            if(DataUtil.TimeDiff(now, ars)<0 || (DataUtil.TimeDiff(now, are)>0 && DataUtil.TimeDiff(now, aurs)<0)){
                return ajaxHtmlAppResult(404, "时间未到，不能签到！", null);
            }

            if(DataUtil.TimeDiff(now, aure)>0){
                return ajaxHtmlAppResult(404, "已过签到时间，不能签到！", null);
            }

        }
        //LogUtil.info("status2 :" +status);

        ProSignIn proSignIn = new ProSignIn();
        proSignIn.setProInfo(proInfo);
        proSignIn.setName(proInfo.getName());
        proSignIn.setCreater(users);
        proSignIn.setCompany(users.getCompany());
        proSignIn.setStatus(status);

        if(StringUtils.isEmpty(latitude) && StringUtils.isEmpty(longitude)){
            return ajaxHtmlAppResult(404, "获取位置失败,请重新签到！", null);
        }
        Locations location=new Locations();
        location.setLatitude(new BigDecimal(latitude));
        location.setLongitude(new BigDecimal(longitude));
        location.setCoordType(EnumManage.CoordTypeEnum.wgs84);
        location.setOpenId(admin.getOpenId());
        proSignInService.saveEntity(proSignIn,location);

        return ajaxHtmlAppResult(1, "签到成功！", null);
    }

    public List<ProInfo> getProInfoList() {
        return proInfoList;
    }

    public void setProInfoList(List<ProInfo> proInfoList) {
        this.proInfoList = proInfoList;
    }

    public ProInfo getProInfo() {
        return proInfo;
    }

    public void setProInfo(ProInfo proInfo) {
        this.proInfo = proInfo;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public String getProStatusType() {
        return proStatusType;
    }

    public void setProStatusType(String proStatusType) {
        this.proStatusType = proStatusType;
    }

    public WxJsapiSignature getJsapiSignature() {
        return jsapiSignature;
    }

    public void setJsapiSignature(WxJsapiSignature jsapiSignature) {
        this.jsapiSignature = jsapiSignature;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public Map<String, List<Map<String, Object>>> getUserListMap() {
        return userListMap;
    }

    public void setUserListMap(Map<String, List<Map<String, Object>>> userListMap) {
        this.userListMap = userListMap;
    }
}
